/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package im.eventservice;

import im.eventpackage.Event;
import im.general.AbstractListenBehaviour;
import im.general.Config;
import im.messages.NotifyRecipientMessage;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author brownstone
 */
public class RecipientsListenBehaviour extends AbstractListenBehaviour {
    EventServiceAgent eventServiceAgent=null;
    public RecipientsListenBehaviour(EventServiceAgent eventServiceAgent) {
        this.eventServiceAgent = eventServiceAgent;
        mt = MessageTemplate.or(MessageTemplate.MatchEncoding(Config.NOTIFY_RECIPIENTS), MessageTemplate.MatchEncoding(Config.NOTIFY_RECIPIENT));
    }

    @Override
    protected void handleMessage(ACLMessage msg) {
        if(msg.getEncoding().equals(Config.NOTIFY_RECIPIENT))
            handleRecipient(msg);
        if(msg.getEncoding().equals(Config.NOTIFY_RECIPIENTS))
            handleRecipients(msg);
    }

    private void handleRecipient(ACLMessage msg) {
        Event e=null;
        try {
            e = (Event) msg.getContentObject();
        } catch (UnreadableException ex) {
            Logger.getLogger(RecipientsListenBehaviour.class.getName()).log(Level.SEVERE, null, ex);
        }

        eventServiceAgent.eventHandler.removeRecipient(e, msg.getSender().getName());
    }

    private void handleRecipients(ACLMessage msg) {
        NotifyRecipientMessage nrmsg = null;
        try {
            nrmsg =  (NotifyRecipientMessage) msg.getContentObject();
        } catch (UnreadableException ex) {
            Logger.getLogger(RecipientsListenBehaviour.class.getName()).log(Level.SEVERE, null, ex);
        }

        eventServiceAgent.eventHandler.removeRecipients(nrmsg.getEvent(), nrmsg.getRecipients());
    }
}
